package org.csu.mall.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import org.csu.mall.common.CONSTANT;
import org.csu.mall.common.UniformResponse;
import org.csu.mall.entity.Cart;
import org.csu.mall.entity.Product;
import org.csu.mall.persistence.CartMapper;
import org.csu.mall.persistence.ProductMapper;
import org.csu.mall.service.ICartService;
import org.csu.mall.utils.BigDecimalUtil;
import org.csu.mall.utils.PropertiesUtil;
import org.csu.mall.utils.UsernameUtil;
import org.csu.mall.vo.CartProductVO;
import org.csu.mall.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    ICartService cartService;

    @Override
    public UniformResponse<CartVO> addCart( Integer productId, Integer quantity) {
        String username = UsernameUtil.getUsername("username");
        Integer userId=Integer.parseInt(UsernameUtil.getUserId("userid"));
        if (username == null) {
            return UniformResponse.notLogining();
        } else {
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("product_id",productId);

            Cart cart = cartMapper.selectOne(queryWrapper);

            if(cart == null){
                //当前购物车中没有该商品，需要新增一个Cart
                Cart newCart = new Cart();
                newCart.setUserId(userId);
                newCart.setQuantity(quantity);
                newCart.setChecked(CONSTANT.CartItemCheckedStatus.SELECTED.getCode());
                newCart.setProductId(productId);
                newCart.setCreateTime(LocalDateTime.now());
                newCart.setUpdateTime(LocalDateTime.now());
                int rows = cartMapper.insert(newCart);
            }else{
                //当前购物车中有该商品，只需要修改数量
                quantity = cart.getQuantity() + quantity;
                cart.setQuantity(quantity);
                cartMapper.updateById(cart);
            }

            CartVO cartVO = getCartVOLimit(userId);

            return UniformResponse.createForSuccess(cartVO);
        }
    }
    @Override
    public UniformResponse<CartVO> updateCart( Integer quantity, Integer productId) {
        String username= UsernameUtil.getUsername("username");
        Integer userId=Integer.parseInt(UsernameUtil.getUserId("userid"));

        if(username==null){
            return UniformResponse.notLogining();
        }else {
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("product_id",productId);

            Cart cart = cartMapper.selectOne(queryWrapper);

            if(cart != null){
                cart.setQuantity(quantity);
                cart.setUpdateTime(LocalDateTime.now());
                cartMapper.updateById(cart);
            }
            CartVO cartVO = getCartVOLimit(userId);

            return UniformResponse.createForSuccess(cartVO);
        }
    }

    @Override
    public UniformResponse<CartVO> deleteCart(Integer productId) {
        String username = UsernameUtil.getUsername("username");
        Integer userId=Integer.parseInt(UsernameUtil.getUserId("userid"));
        if (username == null) {
            return UniformResponse.notLogining();
        } else {
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("product_id",productId);

            Cart cart = cartMapper.selectOne(queryWrapper);
            if (cart == null) {
                return UniformResponse.createForErrorMessage("删除失败");
            }
            cartMapper.deleteById(cart.getId());
            CartVO cartVO = getCartVOLimit(userId);

            return UniformResponse.createForSuccess(cartVO);
        }
    }

    @Override
    public UniformResponse<CartVO> deleteManyCartItems() {
        String username= UsernameUtil.getUsername("username");
        Integer userId=Integer.parseInt(UsernameUtil.getUserId("userid"));
        if(username==null){
            return UniformResponse.notLogining();
        }else {
            List<Integer> cartCheckedIdList=getCheckedIdList(userId);
            if(CollectionUtils.isEmpty(cartCheckedIdList))
            {
                return UniformResponse.createForErrorMessage("未选中商品或购物车为空");
            }

            for (Integer id:cartCheckedIdList) {
                cartMapper.deleteById(id);
            }
            CartVO cartVO = getCartVOLimit(userId);

            return UniformResponse.createForSuccess(cartVO);
        }
    }


    @Override
    public UniformResponse<CartVO> getCartList() {
        Integer userId=Integer.parseInt(UsernameUtil.getUserId("userid"));
        CartVO cartVO = getCartVOLimit(userId);

        return UniformResponse.createForSuccess(cartVO);
    }

    //获取登陆用户的购物车已选中IndexList
    private List<Integer> getCheckedIdList(Integer userId)
    {
        QueryWrapper<Cart> query = new QueryWrapper<>();
        query.eq("user_id",userId).eq("checked", CONSTANT.CartItemCheckedStatus.SELECTED.getCode());
        //查到cart的list
        List<Cart> cartList = cartMapper.selectList(query);
        List<Integer> cartIdList= new ArrayList<>();
        for (Cart cartItem:cartList) {
            cartIdList.add(cartItem.getId());
        }
        return cartIdList;
    }

    private CartVO getCartVOLimit(Integer userId){
        CartVO cartVO = new CartVO();

        //获取该用户的购物车列表
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        List<Cart> cartList = cartMapper.selectList(queryWrapper);

        BigDecimal cartTotalPrice = new BigDecimal("0");

        List<CartProductVO> cartProductVOList = Lists.newArrayList();

        if(CollectionUtils.isNotEmpty(cartList)){
            for(Cart cartItem : cartList){
                CartProductVO cartProductVO = new CartProductVO();
                cartProductVO.setId(cartItem.getId());
                cartProductVO.setUserId(cartItem.getUserId());
                cartProductVO.setProductId(cartItem.getProductId());

                Product product = productMapper.selectById(cartItem.getProductId());

                if(product != null){
                    cartProductVO.setProductMainImage(product.getMainImage());
                    cartProductVO.setProductName(product.getName());
                    cartProductVO.setProductSubtitle(product.getSubtitle());
                    cartProductVO.setProductStatus(product.getStatus());
                    cartProductVO.setProductPrice(product.getPrice());
                    cartProductVO.setProductStock(product.getStock());

                    int buyLimitCount = 0;

                    if(product.getStock() >= cartItem.getQuantity()){
                        buyLimitCount = cartItem.getQuantity();
                        cartProductVO.setLimitQuantity(CONSTANT.LIMIT_NUM_SUCCESS);
                    }else{
                        buyLimitCount = product.getStock();
                        cartProductVO.setLimitQuantity(CONSTANT.LIMIT_NUM_FAILURE);

                        Cart cartForQuantity = new Cart();
                        cartForQuantity.setId(cartItem.getId());
                        cartForQuantity.setQuantity(buyLimitCount);
                        int rows = cartMapper.updateById(cartForQuantity);
                    }
                    cartProductVO.setQuantity(buyLimitCount);
                    cartProductVO.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(),cartProductVO.getQuantity()));
                    cartProductVO.setProductChecked(cartItem.getChecked());
                }
                if(cartItem.getChecked() == CONSTANT.CartItemCheckedStatus.SELECTED.getCode()){
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(),cartProductVO.getProductTotalPrice().doubleValue());
                }
                cartProductVOList.add(cartProductVO);
            }
            cartVO.setCartTotalPrice(cartTotalPrice);
            cartVO.setCartProductVOList(cartProductVOList);
            cartVO.setAllChecked(this.getAllCheckedStatus(userId));
            cartVO.setImageHost(PropertiesUtil.getProperty("image.server.url"));
        }
        return cartVO;
    }

    private boolean getAllCheckedStatus(Integer userId){
        if(userId == null){
            return false;
        }
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(("user_id"),userId);
        queryWrapper.eq("checked",2);
        int result = cartMapper.selectCount(queryWrapper);
        return result == 0;
    }


}
